class User < ActiveRecord::Base
  acts_as_authentic
  acts_as_tree
  
  belongs_to :organization
  belongs_to :status
  belongs_to :employment
  belongs_to :service_branch
  belongs_to :rank
  
  before_destroy :reassign_children
  
  named_scope :active, :conditions => "deleted_at IS NULL"
  named_scope :deleted, :conditions => "deleted_at IS NOT NULL"

  def supervises?(user)
    user.ancestors.include?(self)
  end

  def manually_set_password 
    @manually_set_password
  end
  
  def manually_set_password=(value)
    @manually_set_password = value
  end
  
  def manually_set_password?
    # rails sends values from checkboxes as 1 or 0. the issue is that in Ruby, 0 == true, so we fight that here
    !manually_set_password.to_i.zero?
  end
  
  def full_name
    @full_name ||= "#{self.first_name.capitalize} #{self.last_name.capitalize}"
  end
  
  def official_name
    name_string = "#{self.last_name.capitalize}, #{self.first_name.capitalize}"
    name_string = "#{self.rank.abbr} #{name_string}" if self.rank
    @official_name ||= name_string
  end
  
  def destroy
    self.update_attribute(:deleted_at, DateTime.now)
  end
  
  def restore
    self.update_attribute(:deleted_at, nil)
  end
  
  private
  
  def reassign_children
    new_parent_id = self.root? ? nil : self.parent_id
    self.children.each{|child| child.update_attribute(:parent_id, new_parent_id) }
  end
end
